﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using VitCode.Web.UI.WebControls;

[assembly: TagPrefix("VitCode.Web.UI", "PaginationGrid")]

namespace VitCode.Web.UI
{
    /// <summary>
    ///		PaginationGrid 说明：
    ///		此控件简单的封装了一个ASP.NET的DATAGRID控件，它实现了一个具有分页功能，显示特殊格式的数据，导出数据到EXCEL的表格数据显示容器。
    ///		此控件的列类型：支持普通数据绑定列，支持具有一个复选框的列，支持记录序号列（跨页），支持响应事件的DataGridButton列。
    /// </summary>
    /// 
    [
        Designer(typeof(PaginationGridDesigner)),
        DefaultProperty("Columns"),
        ParseChildren(true),
        ToolboxData("<{0}:PaginationGrid Runat=server></{0}:PaginationGrid>"),
        ToolboxBitmap(typeof(PaginationGrid), "VitCode.Web.UI.bmp")
    ]
    public class PaginationGrid : WebControl, INamingContainer
    {
        #region Delegates

        /// <summary>
        /// 用于提供动态创建PaginationGrid列的方法委托。
        /// </summary>
        public delegate void GridBuildColumnMethodDelegate(PaginationGrid grid, object dataSource);

        /// <summary>
        /// 当控件的分页方式为“自定义”时，用于提供数据源构造器的委托
        /// </summary>
        public delegate PaginationGridDataSourceBuilder GridDataSourceBuilderDelegate();

        /// <summary>
        /// 当控件的分页方式为“标准”时，用于提供数据源的委托
        /// </summary>
        public delegate object GridDataSourceDelegate();

        #endregion

        private const string CSS_ID = "{31590523-5C9B-47f1-B26E-31590523AAAA}";

        private const int EXPORT_MAXRECORDCOUNT = 65500; //导出成Excel时一个Excel文件允许的最大记录量。
        private const string STYLESETSCRIPT_ID = "{31590523-5C9B-47f1-B26E-A5A8AE221EA1}";
        private GridBuildColumnMethodDelegate _buildColumnMethodDelegate;
        private bool _columnIsCreated;
        private PaginationGridColumnCollection _columns;
        private string _DataKeyField = "";
        private GridDataSourceBuilderDelegate _datasourceBuilderDelegate;
        private GridDataSourceDelegate _datasourceDelegate;
        private bool _ExportAllDataEnabled = true;
        private bool _ExportCurrentDataEnabled = true;
        private int _InitPageSize = 5;

        private bool _IsForciblyCreateColumns;

        private PaginationMode _paginationMode = PaginationMode.Normal;
        private int _RecordCount;
        private string _TableHeadCssClass = "";
        private string _TableHeadStyle = "";
        private DropDownList AbbColumnList;

        private HtmlTable BottomTable;
        private HtmlTable CaptionTable;
        private bool gridCaptionVisable = true;
        private DropDownList GridColumnList;
        private object gridDataSource;
        private GridStyle gridStyle = GridStyle.Normal;
        private bool IsHaveButtonColumn;
        private Label lab_Caption;
        private Label lab_curPage;
        private Label lab_totalPage;
        private Label lab_totalRecord;
        private HiddenField m_ClickColumnIndex;
        private ExportDataFileFormat m_DataFileFormat = ExportDataFileFormat.CSV;
        private string m_DataFilePath = "";
        private ImageButton m_FirstButton;
        private ImageButton m_LastButton;
        private ImageButton m_NexButton;
        private ImageButton m_PevButton;
        private DataGrid m_StandGrid;
        private Label OldSortField;
        private TextBox PageNo;
        private DropDownList PageSize;
        private bool showIDColumn;
        private string sourcePath = "~/VitCode_client/PaginationGrid/";
        private ImageButton toolBtn_Print;

        private ImageButton toolButton1;
        private ImageButton toolButton2;
        private ImageButton toolButton3;

        #region 公开的事件

        #region Delegates

        /// <summary>
        /// 导出数据事件句柄。
        /// </summary>
        public delegate void PaginationGridBeforeExportDataEventHandler(
            object sender, PaginationGridBeforeExportDataArgs e);

        /// <summary>
        /// 表格行删除事件句柄。
        /// </summary>
        public delegate void PaginationGridItemDeleteEventHandler(object sender, PaginationGridItemDeleteArgs e);

        /// <summary>
        /// 表格行选中事件句柄。
        /// </summary>
        public delegate void PaginationGridItemSelectEventHandler(object sender, PaginationGridItemSelectArgs e);

        /// <summary>
        /// 表格数据呈现事件句柄。
        /// </summary>
        public delegate void PaginationGridShowDataEventHandler(object sender, PaginationGridShowDataArgs e);

        #endregion

        /// <summary>
        /// 表格行选中事件。当选中表格某一行时发生。
        /// </summary>
        [Category("事件"), Description("当选中表格某一行时发生")]
        public event PaginationGridItemSelectEventHandler OnGridItemSelect;

        /// <summary>
        /// 表格行删除事件。当删除表格某一行时发生。
        /// </summary>
        [Category("事件"), Description("当删除表格某一行时发生")]
        public event PaginationGridItemDeleteEventHandler OnGridItemDelete;

        /// <summary>
        /// 表格数据呈现事件。当表格呈现数据时发生，通过响应此事件，可以更改数据的呈现样式。
        /// </summary>
        [Category("事件"), Description("当表格呈现数据时发生，通过响应此事件，可以更改数据的呈现样式")]
        public event PaginationGridShowDataEventHandler OnGridShowData;

        /// <summary>
        /// 导出数据前事件。在导出表格数据为Excel文件前发生。
        /// </summary>
        /// 
        [Category("事件"), Description("导出数据前事件。在导出表格数据为Excel文件前发生。")]
        public event PaginationGridBeforeExportDataEventHandler OnBeforeExportData;

        #endregion

        /// <summary>
        /// 初始化 PaginationGrid 类的新实例
        /// </summary>
        public PaginationGrid()
        {
            string color = "1665CB";
            int R = Convert.ToInt32(color.Substring(0, 2), 16);
            int G = Convert.ToInt32(color.Substring(2, 2), 16);
            int B = Convert.ToInt32(color.Substring(4, 2), 16);
            GridSelectedItemStyle_BackColor = Color.FromArgb(R, G, B);
            GridSelectedItemStyle_ForeColor = Color.White;
            GridSelectedItemStyle_BorderColor = Color.FromArgb(R, G, B);
            GridBodyBackColor = Color.White;
            GridBodyForeColor = Color.Black;
            string strTemp = sourcePath + "Images/CN/";
            _FirstButtonImgSrcEnable = strTemp + "btn_Enable_First.gif";
            _LastButtonImgSrcEnable = strTemp + "btn_Enable_Last.gif";
            _PevButtonImgSrcEnable = strTemp + "btn_Enable_Pev.gif";
            _NextButtonImgSrcEnable = strTemp + "btn_Enable_Next.gif";
            _FirstButtonImgSrcDisable = strTemp + "btn_Disable_First.gif";
            _LastButtonImgSrcDisable = strTemp + "btn_Disable_Last.gif";
            _PevButtonImgSrcDisable = strTemp + "btn_Disable_Pev.gif";
            _NextButtonImgSrcDisable = strTemp + "btn_Disable_Next.gif";

            try
            {
                string t1 = ConfigurationSettings.AppSettings["PaginationGrid_ExportDataFileFormat"];
                if(!String.IsNullOrEmpty(t1))
                {
                    m_DataFileFormat = (ExportDataFileFormat)Enum.Parse(typeof(ExportDataFileFormat), t1, false);
                }
            }
            catch
            {
                m_DataFileFormat = ExportDataFileFormat.CSV;
            }
        }

        #region 私有方法和受保护的方法

        private string DataFilePath
        {
            get
            {
                try
                {
                    string t1 = ConfigurationSettings.AppSettings["PaginationGrid_ExportDataFilePath"];
                    if (string.IsNullOrEmpty(t1))
                    {
                        m_DataFilePath = HttpContext.Current.Server.MapPath("/VitCode_Client");
                        //m_DataFilePath = Path.GetTempPath();
                    }
                    else
                        m_DataFilePath = t1;
                }
                catch
                {
                    m_DataFilePath = Path.GetTempPath();
                }
                return m_DataFilePath;
            }
        }

        protected override void TrackViewState()
        {
            base.TrackViewState();
            Record("TrackViewState");
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            Record("LoadViewState");
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Record("OnInit 开始");
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Record("OnLoad 开始");
        }

        protected override object SaveViewState()
        {
            object o = base.SaveViewState();
            Record("SaveViewStae,是否为空:" + Convert.ToString(o == null));
            return o;
        }


        /// <summary>
        /// 重载基类的OnPreRender() 方法，这里向客户端注册脚本。
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            //			this.Attributes.Remove("style");
            base.OnPreRender(e);
            RegisterScript();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderEndTag();
        }


        /// <summary>
        /// 用于调试时记录执行信息
        /// </summary>
        /// <param name="item"></param>
        private void Record(string item)
        {
            //var sw = new StreamWriter(@"C:\PaginationGrid.log", true);
            //if (Site != null)
            //    sw.WriteLine(DateTime.Now.ToShortTimeString() + ":" + item + "--" + Site.DesignMode);
            //else
            //    sw.WriteLine(DateTime.Now.ToShortTimeString() + ":" + item);
            //sw.Close();
        }

        /// <summary>
        /// 重写CreateChildControls方法,以创建所有控件
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            ChildControlsCreated = true;
            //m_StandGrid
            m_StandGrid = new DataGrid();
            m_ClickColumnIndex = new HiddenField();
            Controls.Add(m_ClickColumnIndex);
            var col = new BoundColumn();
            col.HeaderStyle.Width = new Unit("5%");
            m_StandGrid.Columns.AddAt(0, col);
            m_StandGrid.AllowPaging = true;
            m_StandGrid.AutoGenerateColumns = false;
            m_StandGrid.AllowSorting = AutoSort;
            m_StandGrid.DataKeyField = DataKeyField;
            m_StandGrid.PagerStyle.Visible = false;
            m_StandGrid.SelectedItemStyle.BackColor = GridSelectedItemStyle_BackColor;
            m_StandGrid.SelectedItemStyle.ForeColor = GridSelectedItemStyle_ForeColor;
            m_StandGrid.SelectedItemStyle.BorderColor = GridSelectedItemStyle_BorderColor;
            //			m_StandGrid.ItemStyle.BackColor = GridBodyBackColor;
            //			m_StandGrid.ItemStyle.ForeColor = GridBodyForeColor;
            //设置表格的默认样式

            m_FirstButton = new ImageButton();
            //m_FirstButton.Attributes["Class"]= _FirstButtonClassName;
            //m_FirstButton.Text = "≤"; //首页
            m_FirstButton.ToolTip = "转到首页";
            m_FirstButton.CausesValidation = false;
            m_PevButton = new ImageButton();
            //m_PevButton.Attributes["Class"] = _PevButtonClassName;
            //m_PevButton.Text = "＜"; //上一页
            m_PevButton.ToolTip = "转到上一页";
            m_PevButton.CausesValidation = false;
            m_NexButton = new ImageButton();
            //m_NexButton.Attributes["Class"] = _NextButtonClassName;
            //m_NexButton.Text = "＞"; //下一页
            m_NexButton.ToolTip = "转到下一页";
            m_NexButton.CausesValidation = false;
            m_LastButton = new ImageButton();
            //m_LastButton.Attributes["Class"] = _LastButtonClassName;
            //m_LastButton.Text = "≥";
            m_LastButton.ToolTip = "转到尾页";
            m_LastButton.CausesValidation = false;
            SetLinkButtonStyle(m_FirstButton);
            SetLinkButtonStyle(m_PevButton);
            SetLinkButtonStyle(m_NexButton);
            SetLinkButtonStyle(m_LastButton);

            PageSizeInit();

            GridColumnList = new DropDownList();
            AbbColumnList = new DropDownList();
            OldSortField = new Label();
            OldSortField.Visible = false;
            lab_curPage = new Label();
            lab_curPage.ID = "CurrentPageIndex";
            lab_totalPage = new Label();
            lab_totalRecord = new Label();
            lab_totalPage.ID = "TotalPageIndex";
            PageNo = new TextBox();
            PageNo.Width = new Unit("40");
            lab_Caption = new Label();
            CaptionTable = new HtmlTable();
            //			CaptionTable.Width = "100%";
            var crow = new HtmlTableRow();
            var ccell = new HtmlTableCell();
            //			ccell.Attributes.Add("align", "center");
            //			ccell.Attributes.Add("style", "font-size:10pt;font-weight:bold");
            ccell.Controls.Add(lab_Caption);
            crow.Cells.Add(ccell);
            CaptionTable.Rows.Add(crow);


            //底部表格
            BottomTable = new HtmlTable();
            BottomTable.Visible = false;
            if (gridStyle == GridStyle.Normal)
            {
                var pgs = new PaginationGridStyle();
                pgs.Width = new Unit("100%");
                pgs.CellSpacing = pgs.CellPadding = 1;
                pgs.Style =
                    "FONT-FAMILY: Arial; font-size:10pt;BORDER-COLLAPSE: collapse;BORDER-RIGHT: #D8D5D3 1px solid;BORDER-TOP: buttonhighlight 1px solid;BORDER-LEFT: buttonhighlight 1px solid;BORDER-BOTTOM: #D8D5D3 1px solid;BACKGROUND-COLOR: #F7F3EF;";
                pgs.Height = new Unit("25");
                SetGridFootStyle(pgs);
            }
            var row = new HtmlTableRow();
            var cell0 = new HtmlTableCell();
            //工具按钮表格定义

            /////
            cell0.Controls.Add(ToolTableInit());
            cell0.Width = "17%";
            cell0.Attributes.Add("style", "BORDER-COLLAPSE: collapse;");
            row.Cells.Add(cell0);
            var recordcell = new HtmlTableCell();
            recordcell.Width = "10%";
            recordcell.InnerText = "记录：";
            recordcell.Controls.Add(lab_totalRecord);
            row.Cells.Add(recordcell);
            var cell2 = new HtmlTableCell();
            cell2.InnerText = "页码：";
            cell2.Controls.Add(lab_curPage);
            var tlab = new Label();
            tlab.Text = "/";
            cell2.Width = "33%";
            cell2.Controls.Add(tlab);
            cell2.Controls.Add(lab_totalPage);
            var tlab1 = new Label();
            tlab1.Text = "　页大小：　";
            cell2.Controls.Add(tlab1);
            cell2.Controls.Add(PageSize);
            cell2.Attributes.Add("style", "BORDER-COLLAPSE: collapse;");
            row.Cells.Add(cell2);

            var cell1 = new HtmlTableCell();
            var table1 = new HtmlTable();
            table1.Width = "100%";
            var table1row = new HtmlTableRow();
            var table1cell0 = new HtmlTableCell();
            table1cell0.Controls.Add(m_FirstButton);
            var table1cell1 = new HtmlTableCell();
            table1cell1.Controls.Add(m_PevButton);
            var table1cell2 = new HtmlTableCell();
            table1cell2.Controls.Add(m_NexButton);
            var table1cell3 = new HtmlTableCell();
            table1cell3.Controls.Add(m_LastButton);
            table1row.Cells.Add(table1cell0);
            table1row.Cells.Add(table1cell1);
            table1row.Cells.Add(table1cell2);
            table1row.Cells.Add(table1cell3);
            table1.Rows.Add(table1row);
            cell1.Controls.Add(table1);
            cell1.Width = "25%";
            row.Cells.Add(cell1);

            var cell3 = new HtmlTableCell();
            cell3.Width = "15%";
            cell3.InnerText = "转到";
            cell3.Controls.Add(PageNo);
            toolButton3 = AddToolButton(sourcePath + "/images/datasearch.gif", "跳转页码");
            cell3.Controls.Add(toolButton3);
            //			cell3.Attributes.Add("style", "BORDER-COLLAPSE: collapse;");
            row.Cells.Add(cell3);
            row.Height = "100%";
            BottomTable.Rows.Add(row);


            m_StandGrid.SortCommand += StandGrid_SortCommand;
            m_StandGrid.ItemDataBound += StandGrid_ItemDataBound;
            m_StandGrid.SelectedIndexChanged += StandGrid_SelectedIndexChanged;
            m_StandGrid.DeleteCommand += StandGrid_DeleteCommand;
            m_StandGrid.ItemCreated += StandGrid_ItemCreated;
            m_FirstButton.Click += Home_Link_Click;
            m_PevButton.Click += Previous_Link_Click;
            m_NexButton.Click += Next_Link_Click;
            m_LastButton.Click += End_Link_Click;
            toolButton1.Click += toolButton1_Click;
            toolButton2.Click += toolButton2_Click;
            toolButton3.Click += toolButton3_Click;
            toolBtn_Print.Attributes.Add("onclick", "javascript:PrintPage('" + ClientID + "');return false;");
            PageSize.SelectedIndexChanged += PageSize_SelectedIndexChanged;


            CaptionTable.Attributes["title"] = "ha001";
            Controls.Add(CaptionTable);

            BuildColumns();

            m_StandGrid.HeaderStyle.CssClass = _trHeadClassName;
            Controls.Add(m_StandGrid);
            BottomTable.Attributes["class"] = _footClassName;

            Controls.Add(BottomTable);
        }

        private void SetDataGridStyle(DataGrid dg)
        {

            dg.Attributes.Remove("style");
            dg.Attributes["class"] = _tableClassName;
            for (int i = 0; i < (dg.Items.Count); i++)
            {
                DataGridItem row = dg.Items[i];
                string className = _trItemClassName; //奇数行的className
                if (i % 2 != 0)
                {
                    className = _trAlItemClassName; //偶数行的ClassName
                }
                row.Attributes["class"] = className;
            }
        }

        private void BuildColumns()
        {
            if (_columnIsCreated == false)
            {
                //先添加自建列
                for (int i = 0; i < Columns.Count; i++)
                {
                    AddColumnToDataGrid(_columns[i]);
                }
                //如果也有自动生成列，则将自动生成的列添加在后面
                if (AutoGenerateColumns)
                {
                    if (gridDataSource != null)
                    {
                        GenerateColumnFromDataSource();
                    }
                    else
                    {
                        GenerateColumnsFromViewState();
                    }
                }
                _columnIsCreated = true;
            }
        }

        private void PageSizeInit()
        {
            PageSize = new DropDownList();
            if (PageSizeOptions.Trim().Length == 0)
            {
                PageSize.Items.Add(new ListItem("5", "5"));
                PageSize.Items.Add(new ListItem("10", "10"));
                PageSize.Items.Add(new ListItem("15", "15"));
                PageSize.Items.Add(new ListItem("20", "20"));
                PageSize.Items.Add(new ListItem("30", "30"));
                PageSize.Items.Add(new ListItem("50", "50"));
            }
            else
            {
                string[] options = PageSizeOptions.Split(',');
                for (int i = 0; i < options.Length; i++)
                {
                    PageSize.Items.Add(new ListItem(options[i], options[i]));
                }
            }
            try
            {
                PageSize.SelectedValue = InitPageSize;
            }
            catch
            {
                //如果找不到匹配项，则用SelectedIndex匹配，此举纯粹是为兼容老版本而做。
                try
                {
                    PageSize.SelectedIndex = Convert.ToInt32(InitPageSize);
                }
                catch
                {
                    PageSize.SelectedIndex = 0;
                }
            }
            PageSize.AutoPostBack = true;
        }

        private void SetToolCellAttr(HtmlTableCell cell)
        {
            cell.Attributes.Add("onmouseover", "this.className='PgListToolButton_3D';");
            cell.Attributes.Add("onmouseout", "this.className='PgListToolButton_Flat';");
            cell.Attributes.Add("onmousedown", "this.className='PgListToolButton_Cancave';");
            cell.Attributes.Add("onmouseup", "this.className='PgListToolButton_Flat';");
        }

        private HtmlTable ToolTableInit()
        {
            var tooltable = new HtmlTable();
            var toolrow = new HtmlTableRow();
            tooltable.CellSpacing = 2;
            tooltable.CellPadding = 1;
            var toolcell0 = new HtmlTableCell();
            toolcell0.Width = "20";
            toolcell0.VAlign = "middle";
            toolcell0.Align = "center";
            SetToolCellAttr(toolcell0);
            if (_ExportCurrentDataEnabled)
            {
                toolButton1 = AddToolButton(sourcePath + "/images/excel.gif", "将本页数据导出到Excel");
            }
            else
            {
                toolButton1 = AddToolButton(sourcePath + "/images/excel_disable.gif", "当前不支持将本页数据导出到Excel");
            }
            toolButton1.Attributes.Add("Enabled", _ExportCurrentDataEnabled.ToString());
            toolButton1.Attributes.Add("onclick", "javascript:return ('True'==this.getAttribute('Enabled'))");
            toolcell0.Controls.Add(toolButton1);
            var toolcell1 = new HtmlTableCell();
            toolcell1.Width = "20";
            toolcell1.Align = "center";
            toolcell1.VAlign = "middle";
            SetToolCellAttr(toolcell1);
            if (_ExportAllDataEnabled)
            {
                toolButton2 = AddToolButton(sourcePath + "/images/excels.gif", "将所有数据导出到Excel");
            }
            else
            {
                toolButton2 = AddToolButton(sourcePath + "/images/excels_disable.gif", "当前不支持将所有数据导出到Excel");
            }
            toolButton2.Attributes.Add("Enabled", _ExportCurrentDataEnabled.ToString());
            toolButton2.Attributes.Add("onclick", "javascript:return ('True'==this.getAttribute('Enabled'))");
            toolcell1.Controls.Add(toolButton2);
            var toolcell2 = new HtmlTableCell();
            toolcell2.Width = "20";
            toolcell2.Align = "center";
            toolcell2.VAlign = "middle";
            SetToolCellAttr(toolcell2);
            toolBtn_Print = AddToolButton(sourcePath + "/images/print.gif", "打印表格中的数据");
            toolBtn_Print.Visible = m_IsCanPrint;
            toolcell2.Controls.Add(toolBtn_Print);

            toolrow.Cells.Add(toolcell0);
            toolrow.Cells.Add(toolcell1);
            toolrow.Cells.Add(toolcell2);
            tooltable.Rows.Add(toolrow);
            return tooltable;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="btn"></param>
        private void SetLinkButtonStyle(ImageButton btn)
        {
            btn.Attributes.Add("onclick", "javascript:return ('True'==this.getAttribute('Enabled'))");
        }


        /// <summary>
        /// 设置“上页”，“下页”等按钮禁用时的状态。
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="enabled"></param>
        /// <param name="enableClassName"></param>
        /// <param name="disableClassName"></param>
        /// <param name="enableImgSrcUrl"></param>
        /// <param name="disableImgSrcUrl"></param>
        private void SetLinkButtonState(ImageButton btn, bool enabled, string enableClassName, string disableClassName,
                                        string enableImgSrcUrl, string disableImgSrcUrl)
        {
            btn.Attributes["Enabled"] = enabled.ToString();
            string tempClassName = "";
            if (enabled)
            {
                tempClassName = enableClassName;
                btn.ImageUrl = enableImgSrcUrl;
            }
            else
            {
                tempClassName = disableClassName;
                btn.ImageUrl = disableImgSrcUrl;
            }
            btn.Attributes["Class"] = tempClassName;
        }

        /// <summary>
        /// 注册需要的客户端脚本，主要用于设置按钮的样式。
        /// </summary>
        private void RegisterScript()
        {
            if (!Page.ClientScript.IsStartupScriptRegistered(CSS_ID))
            {
                Page.ClientScript.RegisterStartupScript(GetType(), STYLESETSCRIPT_ID,
                                                        "<LINK href=\"/VitCode_Client/PaginationGrid/css/pgList.css\" type=\"text/css\" rel=\"stylesheet\">");
            }
            if (!Page.ClientScript.IsStartupScriptRegistered(STYLESETSCRIPT_ID))
            {
                var sb = new StringBuilder();
                sb.Append("<script language=javascript>\n");
                sb.Append("function PaginationGrid_ButtonStyleSet(Style,Element)\n");
                sb.Append("{\n");
                sb.Append("\tif(Element.getAttribute(\"Enabled\")!=null)\n");
                sb.Append("\t{\n");
                sb.Append("\t\tif(Element.getAttribute(\"Enabled\")==\"False\")\n");
                sb.Append("\t\treturn false\n");
                sb.Append("\t}\n");
                sb.Append("\tswitch(Style)\n");
                sb.Append("\t{\n");
                sb.Append("\tcase \"3D\":\n");
                sb.Append("\t\tElement.style.borderRight=\"buttonshadow 1px solid\";\n");
                sb.Append("\t\tElement.style.borderTop=\"buttonhighlight 1px solid\";\n");
                sb.Append("\t\tElement.style.borderLeft=\"buttonhighlight 1px solid\";\n");
                sb.Append("\t\tElement.style.borderBottom=\"buttonshadow 1px solid\";\n\t\tbreak;\n");
                sb.Append("\tcase \"Flat\":\n");
                sb.Append("\t\tElement.style.borderLeft=\"0px\";\n");
                sb.Append("\t\tElement.style.borderBottom=\"0px\";\n");
                sb.Append("\t\tElement.style.borderRight=\"0px\";\n");
                sb.Append("\t\tElement.style.borderTop=\"0px\";\n");
                sb.Append("\t\tbreak;\n");
                sb.Append("\tcase \"Cancave\":\n");
                sb.Append("\t\tElement.style.borderLeft=\"buttonshadow 1px solid\";\n");
                sb.Append("\t\tElement.style.borderBottom=\"buttonhighlight 1px solid\";\n");
                sb.Append("\t\tElement.style.borderRight=\"buttonhighlight 1px solid\";\n");
                sb.Append("\t\tElement.style.borderTop=\"buttonshadow 1px solid\";\n");
                sb.Append("\t\tbreak;\n");
                sb.Append("\t}\n");
                sb.Append("}\n");

                sb.Append("\tfunction PrintPage(dataGrid)\n");
                sb.Append("\t{\n");
                string strPath = sourcePath;
                if (strPath.StartsWith("~"))
                    strPath = strPath.Remove(0, 1);
                sb.Append("\t\twindow.open('" + strPath +
                          "PrintControl.htm',dataGrid,'width=330,height=235,scrollbars=no,status=no')\n");
                sb.Append("\t}\n");
                sb.Append("function SelectAllCheckColumn()\n{");
                sb.Append("/*此方法选择 PaginationGrid 中复选框列的所有行 */\n");
                sb.Append("	var checkboxid=window.event.srcElement.id;\n");
                sb.Append("	var grid=window.event.srcElement.parentElement.parentElement.parentElement;\n");
                sb.Append("	var head=grid.rows[0];\n");
                sb.Append("	var checkboxcolumnIndex=-1;\n");
                sb.Append("	//得到复选框列所在的索引\n");
                sb.Append("	for(i=0;i<head.cells.length;i++)\n");
                sb.Append("{\nif(checkboxid==head.cells[i].childNodes[0].id)\n");
                sb.Append("\t{\n\t	checkboxcolumnIndex=i;\n");
                sb.Append("break;\n}\n}\n");
                sb.Append("	var checked=window.event.srcElement.getAttribute(\"Checked\");\n");
                sb.Append("for(i=1;i<grid.rows.length;i++)\n");
                sb.Append(
                    "{\n\tif(checked!=grid.rows[i].cells[checkboxcolumnIndex].childNodes[0].getAttribute(\"Checked\"))\n");
                sb.Append("\t\t	grid.rows[i].cells[checkboxcolumnIndex].childNodes[0].click();\n}\n}");
                sb.Append("</script>\n");
                Page.ClientScript.RegisterStartupScript(Page.GetType(), STYLESETSCRIPT_ID, sb.ToString());
            }
        }

        /// <summary>
        /// 当AutoGenerateColumns=true时，用于从已保存的ViewState中生成表格列。在页面非第一次运行时执行。
        /// </summary>
        private bool GenerateColumnsFromViewState()
        {
            if (ViewState["GridColumns"] != null)
            {
                string[] columns = ViewState["GridColumns"].ToString().Split(';');
                for (int i = 0; i < columns.Length; i++)
                {
                    AddColumnToDataGrid(new PaginationGridBoundColumn(columns[i].Split(',')[0], columns[i].Split(',')[1]));
                }
                return true;
            }
            return false;
        }

        /// <summary>
        ///  当AutoGenerateColumns=true时，用于从已保存当前数据源生成表格列。
        /// </summary>
        private bool GenerateColumnFromDataSource()
        {
            object data = gridDataSource;
            if (gridDataSource is DataTable)
            {
                data = ((DataTable)gridDataSource).DefaultView;
            }
            if (gridDataSource is DataSet)
            {
                data = ((DataSet)gridDataSource).Tables[0].DefaultView;
            }
            if (gridDataSource is Hashtable)
                data = gridDataSource;
            if (gridDataSource is Array)
            {
                //数组
                AddColumnToDataGrid(new PaginationGridBoundColumn("!", "Item"));
                ViewState["GridColumns"] = "!,Item";
                _columns.Add(new PaginationGridBoundColumn("!", "Item"));
                return true;
            }

            if (data is DbDataRecord)
            {
                //数据源为DataReader时
                var record = (DbDataRecord)data;
                var columns = new string[record.FieldCount];
                for (int i = 0; i < record.FieldCount; i++)
                {
                    columns[i] = record.GetName(i) + "," + record.GetName(i);
                    AddColumnToDataGrid(new PaginationGridBoundColumn(record.GetName(i), record.GetName(i)));
                    _columns.Add(new PaginationGridBoundColumn(record.GetName(i), record.GetName(i)));
                }
                if (columns.Length > 0)
                {
                    ViewState["GridColumns"] = String.Join(";", columns);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            if (data is DataView)
            {
                var ss = data as DataView;
                var columns = new string[ss.Table.Columns.Count];
                for (int colIndex = 0; colIndex < ss.Table.Columns.Count; colIndex++)
                {
                    columns[colIndex] = ss.Table.Columns[colIndex].ColumnName + "," +
                                        ss.Table.Columns[colIndex].ColumnName;
                    AddColumnToDataGrid(
                        new PaginationGridBoundColumn(ss.Table.Columns[colIndex].ColumnName,
                                                      ss.Table.Columns[colIndex].ColumnName));
                    _columns.Add(
                        new PaginationGridBoundColumn(ss.Table.Columns[colIndex].ColumnName,
                                                      ss.Table.Columns[colIndex].ColumnName));
                }
                if (columns.Length > 0)
                {
                    ViewState["GridColumns"] = String.Join(";", columns);
                    return true;
                }
                else
                    return false;
            }
            if (data is DictionaryEntry)
            {
                //哈希表
                AddColumnToDataGrid(new PaginationGridBoundColumn("Key", "键"));
                AddColumnToDataGrid(new PaginationGridBoundColumn("Value", "值"));
                ViewState["GridColumns"] = "Key,键;Value,值";
                _columns.Add(new PaginationGridBoundColumn("Key", "键"));
                _columns.Add(new PaginationGridBoundColumn("Value", "值"));
                return true;
            }
            if (data is ArrayList || data is IList)
            {
                //ArrayList
                AddColumnToDataGrid(new PaginationGridBoundColumn("!", "Item"));
                ViewState["GridColumns"] = "!,Item";
                _columns.Add(new PaginationGridBoundColumn("!", "Item"));
                return true;
            }
            if (data.GetType().Namespace == "System")
            {
                //可能是基本数据类型,如 System.String
                AddColumnToDataGrid(new PaginationGridBoundColumn("!", "Item"));
                ViewState["GridColumns"] = "!,Item";
                _columns.Add(new PaginationGridBoundColumn("!", "Item"));
                return true;
            }
            else
            {
                //如果是一个对象的实例
                Type tp = data.GetType();
                PropertyInfo[] pis = tp.GetProperties();
                var columns = new string[pis.Length];
                int colIndex = 0;
                foreach (PropertyInfo pi in pis)
                {
                    columns[colIndex] = pi.Name + "," + pi.Name;
                    AddColumnToDataGrid(new PaginationGridBoundColumn(pi.Name, pi.Name));
                    _columns.Add(new PaginationGridBoundColumn(pi.Name, pi.Name));
                    colIndex++;
                }
                if (colIndex > 0)
                {
                    ViewState["GridColumns"] = String.Join(";", columns);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 当AutoGenerateColumns=true时，用于在数据源发生改变时重新生成表格列。因为此时的数据源架构可能已经更改。
        /// </summary>
        private void ResetColumns()
        {
            //重新创建数据列
            if (_IsForciblyCreateColumns && AutoGenerateColumns)
            {
                //首先移除旧数据源的列，但不移除自建列
                if (ViewState["GridColumns"] != null)
                {
                    string[] columns = ViewState["GridColumns"].ToString().Split(';');
                    for (int i = 0; i < columns.Length; i++)
                    {
                        for (int col = m_StandGrid.Columns.Count - 1; col > 0; col--)
                        {
                            if (m_StandGrid.Columns[col].HeaderText == columns[i].Split(',')[1])
                            {
                                m_StandGrid.Columns.RemoveAt(col);
                            }
                        }
                    }
                }
                //再添加新数据源列
                _columnIsCreated = GenerateColumnFromDataSource();
            }
        }


        /// <summary>
        /// 将列添加到内部DataGrid中。
        /// </summary>
        /// <param name="column">一个实现 IPaginationGridColumn接口并从DataGridColumn继承的列。</param>
        private void AddColumnToDataGrid(IPaginationGridColumn column)
        {
            m_StandGrid.Columns.Add((DataGridColumn)column);
            if (AutoSort)
            {
                ((DataGridColumn)column).SortExpression = (column).ColumnDataField;
            }
            string FormatString = column.ColumnTextFormatString;
            if (FormatString.ToLower().IndexOf("abb") >= 0)
            {
                if (column.GetType() == typeof(PaginationGridBoundColumn))
                {
                    ((PaginationGridBoundColumn)column).DataFormatString = "";
                }
                string tempString = FormatString.Replace("{", "").Replace("}", "");
                AbbColumnList.Items.Add(new ListItem(column.ColumnHeaderText, tempString.Split(':')[1]));
            }
            if (column is PaginationGridButtonColumn)
            {
                IsHaveButtonColumn = true;
                //如果列是命令列，并且没有为其设置 DataTextField 属性，则在导出时不导出此列。
                if (((PaginationGridButtonColumn)column).DataTextField.Trim().Length == 0)
                    return;
            }
            if (column is PaginationGridLinkColumn)
            {
                //如果列是命令列，并且没有为其设置 DataField 属性，则在导出时不导出此列。
                if (((PaginationGridLinkColumn)column).DataField.Trim().Length == 0)
                    return;
            }
            if (column is PaginationGridCheckColumn)
                return;
            if (((DataGridColumn)column).Visible == false)
                return;
            var li = new ListItem(column.ColumnHeaderText, column.ColumnDataField);
            GridColumnList.Items.Add(li);
        }

        /// <summary>
        /// 产生当前的排序行为。
        /// </summary>
        private void BuildSortMode(DataView view)
        {
            if (SortExpression.Length == 0)
            {
                string SortString = view.Sort;
                if (SortString.Length > 0)
                {
                    string[] tempAry;
                    tempAry = SortString.Split(new[] { ' ' });
                    if (tempAry.Length > 1)
                    {
                        SortMode = tempAry[1];
                    }
                }
                SortExpression = view.Sort;
            }
            else
            {
                if (SortExpression.IndexOf(",", 0) > 0)
                {
                    //如果指定了多个排序字段而且是 AutoSort 属性为 True时，则只取第一个字段排序。
                    string[] temp = SortExpression.Split(',');
                    if (AutoSort)
                    {
                        SortExpression = temp[0];
                        if (temp[0].Split(' ').Length > 1)
                            SortMode = temp[0].Split(' ')[1];
                        else
                            SortMode = "asc";
                    }
                }
                try
                {
                    view.Sort = SortExpression;
                }
                catch
                {
                    //可能数据架构已经更改，则将现有的排序字段清空。
                    view.Sort = "";
                    OldSortField.Text = "";
                    ViewState["SortExpression"] = "";
                    ViewState["SortMode"] = "";
                }
            }
        }

        /// <summary>
        /// 决议出绑定表格所需要的数据源，如果数据源是DataSet或DataTable类型时，将会把它转换为DataView
        /// </summary>
        /// <returns>数据源的最大记录数量。</returns>
        private int ResolveDataSource()
        {
            int recordCount = 0;
            if (gridDataSource != null)
            {
                string typeName = GetDataSourceTypeName(gridDataSource);
                switch (typeName)
                {
                    case "DataView":
                        BuildSortMode((DataView)gridDataSource);
                        recordCount = ((DataView)gridDataSource).Count;
                        break;
                    case "ArrayList":
                        recordCount = ((ArrayList)gridDataSource).Count;
                        break;
                    case "Hashtable":
                        recordCount = ((ICollection)gridDataSource).Count;
                        AutoGenerateColumns = true;
                        break;
                    case "SqlDataReader":
                        AllowPage = false;
                        m_StandGrid.AllowPaging = false;
                        break;
                    case "DataTable":
                        var table = (DataTable)gridDataSource;
                        if (_paginationMode == PaginationMode.Customize)
                            recordCount = _RecordCount;
                        else
                            recordCount = table.Rows.Count;
                        BuildSortMode(((DataTable)gridDataSource).DefaultView);
                        gridDataSource = ((DataTable)gridDataSource).DefaultView;
                        break;
                    case "IList":
                        recordCount = ((IList)gridDataSource).Count;
                        AutoGenerateColumns = true;
                        break;
                    default:
                        if (gridDataSource is Array)
                        {
                            //如果数据源是数组
                            recordCount = ((Array)gridDataSource).Length;
                        }
                        else
                        {
                            try
                            {
                                var ds = (DataSet)gridDataSource;
                                recordCount = ds.Tables[0].Rows.Count;
                                DataView dView = ds.Tables[0].DefaultView;
                                BuildSortMode(dView);
                                gridDataSource = dView;
                            }
                            catch (Exception ex)
                            {
                                throw new PaginationGridException("绑定数据出错", ex);
                            }
                        }
                        break;
                }
            }
            return recordCount;
        }

        /// <summary>
        /// 得到对象的类型名
        /// </summary>
        /// <param name="dataSource"></param>
        /// <returns></returns>
        private string GetDataSourceTypeName(object dataSource)
        {
            if (dataSource is DataView)
                return "DataView";
            if (dataSource is ArrayList)
                return "ArrayList";
            if (dataSource is Hashtable)
                return "Hashtable";
            if (dataSource is SqlDataReader)
                return "SqlDataReader";
            if (dataSource is DataTable)
                return "DataTable";
            if (dataSource is IList)
                return "IList";
            return "";
        }

        /// <summary>
        /// 执行数据绑定。
        /// </summary>
        /// <param name="Rebinding">是否需要重新绑定数据</param>
        /// <param name="InitPageIndex">绑定时的初始页索引,如果是-1表示页码不变</param>
        /// <returns></returns>
        private bool BindData(bool Rebinding, int InitPageIndex)
        {
            if (Rebinding)
            {
                EnsureChildControls();
            }
            object dataSource;
            if (_paginationMode == PaginationMode.Normal)
            {
                if (_datasourceDelegate == null)
                {
                    throw new ArgumentNullException("没有设置 DataSourceDelegate 属性");
                }
                dataSource = _datasourceDelegate();
            }
            else
            {
                //分页模式是“自定义”
                if (_datasourceBuilderDelegate == null)
                {
                    throw new ArgumentNullException("没有设置 DataSourceBuilderDelegate 属性");
                }
                PaginationGridDataSourceBuilder builder = _datasourceBuilderDelegate();
                builder.PageIndex = CurrentPageIndex;
                builder.PageSize = CurrentPageSize;
                builder.SortExpression = SortExpression;
                dataSource = builder.BuildDataSource();
                _RecordCount = builder.RecordCount;
                m_StandGrid.AllowCustomPaging = true;
            }

            if (dataSource == null)
                throw new ArgumentNullException("获取的数据源对象为空");
            gridDataSource = dataSource;

            if (_buildColumnMethodDelegate != null)
            {
                //如果提供了委托方法，通过委托，动态创建列。
                _buildColumnMethodDelegate(this, dataSource);
                BuildColumns();
            }
            if (Rebinding)
            {
                //在自动生成列时，当需要重新绑定数据时，重新创建列
                _IsForciblyCreateColumns = true;
                ResetColumns();
                if (SortExpression.Length > 0)
                    ShowSortFlag();
            }
            m_StandGrid.Columns[0].Visible = showIDColumn;
            try
            {
                m_StandGrid.VirtualItemCount = ResolveDataSource();
                m_StandGrid.DataSource = gridDataSource;
                m_StandGrid.PageSize = Convert.ToInt32(PageSize.SelectedItem.Text);
                if (Rebinding)
                {
                    int pagecount = m_StandGrid.VirtualItemCount / m_StandGrid.PageSize + 1;
                    if (InitPageIndex > (pagecount - 1))
                        InitPageIndex = pagecount - 1;
                    m_StandGrid.CurrentPageIndex = InitPageIndex;
                }
                m_StandGrid.DataBind();
                SetLinkState();
                BottomTable.Visible = (m_StandGrid.Items.Count > 0 && AllowPage);
                if (AllowPage)
                {
                    BottomTable.Visible = true;
                }
                if (GridCaptionVisable)
                {
                    lab_Caption.Text = GridCaption;
                    lab_Caption.Visible = true;
                }
                SetDataGridStyle(m_StandGrid);
                return true;
            }
            catch (Exception ex)
            {
                BottomTable.Visible = false;
                throw new PaginationGridException("绑定数据出错", ex);
            }
        }

        /// <summary>
        /// 显示排序列的排序标志
        /// </summary>
        private void ShowSortFlag()
        {
            if (!AutoSort)
                return;
            String strOrder = (SortMode == "asc" ? " 5" : " 6");
            string oldStrOrder = (SortMode == "desc" ? " 5" : " 6");
            string sortField = "";
            sortField = SortExpression.Split(' ')[0];
            for (int i = 0; i < m_StandGrid.Columns.Count; i++)
            {
                if (m_StandGrid.Columns[i] is PaginationGridCheckColumn)
                    continue;
                if (sortField.ToLower() == m_StandGrid.Columns[i].SortExpression.ToLower())
                {
                    if (m_StandGrid.Columns[i].HeaderText.IndexOf("  <font", 0) < 0)
                    {
                        m_StandGrid.Columns[i].HeaderText += "  <font face=webdings>" + strOrder + "</font>";
                    }
                    else
                    {
                        m_StandGrid.Columns[i].HeaderText =
                            m_StandGrid.Columns[i].HeaderText.Substring(0,
                                                                        m_StandGrid.Columns[i].HeaderText.IndexOf(
                                                                            "  <font", 0)) +
                            "  <font face=webdings>" + strOrder + "</font>";
                    }
                    if (OldSortField.Text == "")
                    {
                        break;
                    }
                }
                if (OldSortField.Text.ToLower() != sortField.ToLower() &&
                    OldSortField.Text.ToLower() == m_StandGrid.Columns[i].SortExpression.ToLower())
                {
                    if (m_StandGrid.Columns[i].HeaderText.IndexOf("  <font", 0) > 0)
                    {
                        m_StandGrid.Columns[i].HeaderText =
                            m_StandGrid.Columns[i].HeaderText.Substring(0,
                                                                        m_StandGrid.Columns[i].HeaderText.IndexOf(
                                                                            "  <font", 0));
                    }
                }
            }
        }

        /// <summary>
        /// 得到具有缩略内容的列的实际显示内容
        /// </summary>
        /// <param name="MarkString">列的HTML串</param>
        /// <returns>返回提取到的实际内容,若提取不成功,则返回原串</returns>
        private string GetTitle(string MarkString)
        {
            Regex r;
            Match m;
            string tempString = "";
            tempString = MarkString;
            r = new Regex("title\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
                          RegexOptions.IgnoreCase | RegexOptions.Compiled);
            m = r.Match(tempString);
            if (m.Success)
            {
                tempString = m.Groups[1].ToString();
            }
            return tempString;
        }

        /// <summary>
        /// 得到超连接列的实际内容
        /// </summary>
        /// <param name="MarkString">列的HTML串</param>
        /// <returns></returns>
        private string GetLinkContext(string MarkString)
        {
            string tempString = Regex.Replace(MarkString, @"<[^>]+>", "");
            return tempString;
        }


        private ImageButton AddToolButton(string ImgUrl, string TipText)
        {
            var ig0 = new ImageButton();
            ig0.ImageUrl = ImgUrl;
            ig0.AlternateText = TipText;
            ig0.Attributes.Add("OnCommand", "Export");
            ig0.CausesValidation = false;
            ig0.Attributes.Add("align", "AbsMiddle");
            ig0.Attributes.Add("OnFocus", "javascript:this.blur();");
            return ig0;
        }

        /// <summary>
        /// 此方法将测试一个文本框的内容是不是一个有效的数字
        /// </summary>
        /// <param name="objText">要测试的文本框</param>
        /// <returns>如果文本框中是有效数字,则返回该数值,否则返回0</returns>
        private int FormatNumber(TextBox objText)
        {
            if (objText.Text.Trim().Length == 0)
            {
                objText.Text = "0";
                return 0;
            }
            else
            {
                try
                {
                    int t = Convert.ToInt32(objText.Text);
                    return t;
                }
                catch
                {
                    objText.Text = "0";
                    return 0;
                }
            }
        }


        /// <summary>
        /// 设置"上一页,下一页,首页,尾页"的可用状态和更新当前页码
        /// </summary>
        private void SetLinkState()
        {
            lab_curPage.Text = Convert.ToString(m_StandGrid.CurrentPageIndex + 1);
            lab_totalPage.Text = m_StandGrid.PageCount.ToString();
            lab_totalRecord.Text = m_StandGrid.VirtualItemCount.ToString();

            if (m_StandGrid.CurrentPageIndex == 0)
            {
                SetLinkButtonState(m_FirstButton, false, _FirstButtonClassNameEnable, _FirstButtonClassNameDisable,
                                   _FirstButtonImgSrcEnable, _FirstButtonImgSrcDisable);
                SetLinkButtonState(m_PevButton, false, _PevButtonClassNameEnable, _PevButtonClassNameDisable,
                                   _PevButtonImgSrcEnable, _PevButtonImgSrcDisable);
            }
            else
            {
                SetLinkButtonState(m_FirstButton, true, _FirstButtonClassNameEnable, _FirstButtonClassNameDisable,
                                   _FirstButtonImgSrcEnable, _FirstButtonImgSrcDisable);
                SetLinkButtonState(m_PevButton, true, _PevButtonClassNameEnable, _PevButtonClassNameDisable,
                                   _PevButtonImgSrcEnable, _PevButtonImgSrcDisable);
            }
            if (m_StandGrid.CurrentPageIndex == m_StandGrid.PageCount - 1)
            {
                SetLinkButtonState(m_LastButton, false, _LastButtonClassNameEnable, _LastButtonClassNameDisable,
                                   _LastButtonImgSrcEnable, _LastButtonImgSrcDisable);
                SetLinkButtonState(m_NexButton, false, _NextButtonClassNameEnable, _NextButtonClassNameDisable,
                                   _NextButtonImgSrcEnable, _NextButtonImgSrcDisable);
            }
            else
            {
                SetLinkButtonState(m_LastButton, true, _LastButtonClassNameEnable, _LastButtonClassNameDisable,
                                   _LastButtonImgSrcEnable, _LastButtonImgSrcDisable);
                SetLinkButtonState(m_NexButton, true, _NextButtonClassNameEnable, _NextButtonClassNameDisable,
                                   _NextButtonImgSrcEnable, _NextButtonImgSrcDisable);
            }
        }

        private string FetchDataFieldName(string headertext)
        {
            int at = headertext.ToLower().IndexOf("<font");
            if (at > 0)
            {
                return headertext.Substring(0, at - 1).Trim();
            }
            return headertext.Trim();
        }

        private string NameValueCollectionToString(NameValueCollection collection)
        {
            var ary = new string[collection.Count];
            for (int i = 0; i < collection.Count; i++)
            {
                ary[i] = collection.Keys[i] + "," + collection[i];
            }
            return String.Join(";", ary);
        }

        private NameValueCollection StringToNameValueCollection(string valuestring)
        {
            var collection = new NameValueCollection();
            string[] headAry = valuestring.Split(';');
            for (int i = 0; i < headAry.Length; i++)
            {
                collection.Add(headAry[i].Split(',')[0], headAry[i].Split(',')[1]);
            }
            return collection;
        }

        #endregion

        #region 公开的属性

        private string _FirstButtonClassNameDisable = "DefaultPgListFirstButtonImgSrcDisable";
        private string _FirstButtonClassNameEnable = "DefaultPgListFirstButtonStyleEnable";
        private string _FirstButtonImgSrcDisable;
        private string _FirstButtonImgSrcEnable;
        private string _footClassName = "DefaultPgListFootStyle";
        private string _LastButtonClassNameDisable = "DefaultPgListLastButtonImgSrcDisable";
        private string _LastButtonClassNameEnable = "DefaultPgListLastButtonStyleEnable";
        private string _LastButtonImgSrcDisable;
        private string _LastButtonImgSrcEnable;
        private string _NextButtonClassNameDisable = "DefaultPgListNextButtonImgSrcDisable";
        private string _NextButtonClassNameEnable = "DefaultPgListNextButtonStyleEnable";
        private string _NextButtonImgSrcDisable;
        private string _NextButtonImgSrcEnable;
        private string _PevButtonClassNameDisable = "DefaultPgListPevButtonImgSrcDisable";
        private string _PevButtonClassNameEnable = "DefaultPgListPevButtonStyleEnable";
        private string _PevButtonImgSrcDisable;
        private string _PevButtonImgSrcEnable;
        private string _tableClassName = "DefaultPgListTableStyle";
        private string _trAlItemClassName = "DefaultPgListTrAlItemStyle";

        private string _trHeadClassName = "DefaultPgListTrHeadStyle";

        private string _trItemClassName = "DefaultPgListTrItemStyle";
        private bool m_ContinueExport = true;
        private NameValueCollection m_ExportFooter = new NameValueCollection();
        private NameValueCollection m_ExportHeader = new NameValueCollection();
        private bool m_IsCanPrint = false;
        [Category("样式"), Description("列表.class类名")]
        public string TableClassName
        {
            get { return _tableClassName; }
            set { _tableClassName = value; }
        }

        [Category("样式"), Description("表头.class类名")]
        public string TrHeadClassName
        {
            get { return _trHeadClassName; }
            set { _trHeadClassName = value; }
        }

        [Category("样式"), Description("单元格.class类名")]
        public string TrItemClassName
        {
            get { return _trItemClassName; }
            set { _trItemClassName = value; }
        }

        [Category("样式"), Description("单元格.class类名")]
        public string TrAlClassName
        {
            get { return _trAlItemClassName; }
            set { _trAlItemClassName = value; }
        }

        [Category("样式"), Description("表脚.class类名")]
        public string FootClassName
        {
            get { return _footClassName; }
            set { _footClassName = value; }
        }

        [Category("样式"), Description("下一页按钮.class类名")]
        public string NextButtonClassNameEnable
        {
            get { return _NextButtonClassNameEnable; }
            set { _NextButtonClassNameEnable = value; }
        }

        [Category("样式"), Description("上一页按钮.class类名")]
        public string PevButtomClassNameEnable
        {
            get { return _PevButtonClassNameEnable; }
            set { _PevButtonClassNameEnable = value; }
        }

        [Category("样式"), Description("首页按钮.class类名")]
        public string FirstButtomClassNameEnable
        {
            get { return _FirstButtonClassNameEnable; }
            set { _FirstButtonClassNameEnable = value; }
        }

        [Category("样式"), Description("尾页按钮.class类名")]
        public string LastButtomClassNameEnable
        {
            get { return _LastButtonClassNameEnable; }
            set { _LastButtonClassNameEnable = value; }
        }

        [Category("样式"), Description("下一页按钮,底图SRC")]
        public string NextButtonClassNameDisable
        {
            get { return _NextButtonClassNameDisable; }
            set { _NextButtonClassNameDisable = value; }
        }

        [Category("样式"), Description("上一页按钮,底图SRC")]
        public string PevButtomClassNameDisable
        {
            get { return _PevButtonClassNameDisable; }
            set { _PevButtonClassNameDisable = value; }
        }

        [Category("样式"), Description("首页按钮,底图SRC")]
        public string FirstButtomClassNameDisable
        {
            get { return _FirstButtonClassNameDisable; }
            set { _FirstButtonClassNameDisable = value; }
        }

        [Category("样式"), Description("尾页按钮,底图SRC")]
        public string LastButtomClassNameDisable
        {
            get { return _LastButtonClassNameDisable; }
            set { _LastButtonClassNameDisable = value; }
        }

        [Category("样式"), Description("下一页按钮,底图SRC")]
        public string NextButtonImgSrcEnable
        {
            get { return _NextButtonImgSrcEnable; }
            set { _NextButtonImgSrcEnable = value; }
        }

        [Category("样式"), Description("上一页按钮,底图SRC")]
        public string PevButtomImgSrcEnable
        {
            get { return _PevButtonImgSrcEnable; }
            set { _PevButtonImgSrcEnable = value; }
        }

        [Category("样式"), Description("首页按钮,底图SRC")]
        public string FirstButtomImgSrcEnable
        {
            get { return _FirstButtonImgSrcEnable; }
            set { _FirstButtonImgSrcEnable = value; }
        }

        [Category("样式"), Description("尾页按钮,底图SRC")]
        public string LastButtomImgSrcEnable
        {
            get { return _LastButtonImgSrcEnable; }
            set { _LastButtonImgSrcEnable = value; }
        }

        [Category("样式"), Description("下一页按钮.class类名")]
        public string NextButtonImgSrcDisable
        {
            get { return _NextButtonImgSrcDisable; }
            set { _NextButtonImgSrcDisable = value; }
        }

        [Category("样式"), Description("上一页按钮.class类名")]
        public string PevButtomImgSrcDisable
        {
            get { return _PevButtonImgSrcDisable; }
            set { _PevButtonImgSrcDisable = value; }
        }

        [Category("样式"), Description("首页按钮.class类名")]
        public string FirstButtomImgSrcDisable
        {
            get { return _FirstButtonImgSrcDisable; }
            set { _FirstButtonImgSrcDisable = value; }
        }

        [Category("样式"), Description("尾页按钮.class类名")]
        public string LastButtomImgSrcDisable
        {
            get { return _LastButtonImgSrcDisable; }
            set { _LastButtonImgSrcDisable = value; }
        }
        [Category("设置"), Description("iFram 临时面页路径")]
        public string TempFrmCallPagePath
        {
            get { return m_TempFrmCallPagePath; }
            set { m_TempFrmCallPagePath = value; }
        }
        /// <summary>
        /// 控件的数据分页方式。
        /// </summary>
        /// 
        [
            Category("行为"),
            Description("数据分页方式，标准方式：采用DataGrid自己的分页模式；自定义分页：通过继承PaginationGridDataSourceBuilder 实现自定义的分页方式。")
        ]
        public PaginationMode DataPaginationMode
        {
            get { return _paginationMode; }
            set
            {
                if (Enum.IsDefined(typeof(PaginationMode), value))
                {
                    _paginationMode = value;
                }
            }
        }

        /// <summary>
        /// 获取或设置排序字段表达式。格式为：字段名 [空格] 排序方式，如“Field asc”，表示以升序方式按Field排序。如果要对多字段排序，中间用“,”号分隔，如“Field1 asc,Field2 desc”。
        /// 当设置AutoSort属性为True时，则只对第一个字段排序。即此时不支持多字段排序。
        /// 此属性可能在运行改变，点击表头时，就会更改此属性的值。
        /// </summary>
        /// 
        [
            Category("数据"),
            Description(
                "获取或设置排序字段表达式。格式为：字段名 [空格] 排序方式，如“Field asc”，表示以升序方式按Field排序。如果要对多字段排序，中间用“,”号分隔，如“Field1 asc,Field2 desc”。当设置AutoSort属性为True时，则只对第一个字段排序。即此时不支持多字段排序。此属性可能在运行改变，点击表头时，就会更改此属性的值。"
                )
        ]
        public string SortExpression
        {
            get
            {
                if (ViewState["SortExpression"] == null)
                    return "";
                else
                    return Convert.ToString(ViewState["SortExpression"]);
            }
            set { ViewState["SortExpression"] = value; }
        }

        /// <summary>
        /// 获取或设置排序方式（升序或降序，默认为升序）。此属性可能在运行改变，如当表格支持自动排序时，点击表头时，就会更改此属性的值。
        /// </summary>
        /// 
        [
            Browsable(false)
        ]
        public string SortMode
        {
            get
            {
                if (ViewState["SortExpression"] == null)
                    return "asc";
                else
                {
                    if (ViewState["SortMode"] == null)
                    {
                        string temp = Convert.ToString(ViewState["SortExpression"]);
                        string[] tempary = temp.Split(',');
                        if (tempary.Length >= 1)
                        {
                            if (tempary[0].Split(' ').Length > 1)
                            {
                                string sort = tempary[0].Split(' ')[1];
                                if (sort.ToLower() != "desc" && sort.ToLower() != "asc")
                                    throw new ArgumentException("错误的排序方式，只能是asc 或 desc", "SortMode");
                                else
                                    return sort;
                            }
                            else
                                return "asc";
                        }
                        else
                            return "asc";
                    }
                    else
                        return Convert.ToString(ViewState["SortMode"]);
                }
            }
            set
            {
                if (value.Trim().Length == 0)
                    value = "asc";
                ViewState["SortMode"] = value;
            }
        }

        /// <summary>
        /// 初始页记录条数。
        /// </summary>
        /// 
        [
            Category("数据"),
            Description("初始页大小。"),
            TypeConverter(typeof(InitPageSizePropertyTypeConverter))
        ]
        public string InitPageSize
        {
            get { return _InitPageSize.ToString(); }
            set { _InitPageSize = Convert.ToInt32(value); }
        }

        /// <summary>
        /// 获取当前页上允许的记录数量。
        /// </summary>
        /// 
        [Browsable(false)]
        public int CurrentPageSize
        {
            get
            {
                if (PageSize == null)
                    return 0;
                else
                    return Convert.ToInt32(PageSize.SelectedValue);
            }
        }

        /// <summary>
        /// 获取当前页索引。
        /// </summary>
        [Browsable(false)]
        public int CurrentPageIndex
        {
            get { return CurrentGrid.CurrentPageIndex; }
        }

        /// <summary>
        /// 获取或设置页大小列表框的项。
        /// </summary>
        /// 
        [Browsable(false)]
        public string PageSizeOptions
        {
            get
            {
                if (ViewState["PageSizeOptions"] != null)
                {
                    return Convert.ToString(ViewState["PageSizeOptions"]);
                }
                else
                {
                    return "";
                }
            }
            set { ViewState["PageSizeOptions"] = value; }
        }

        /// <summary>
        /// PaginationGrid 中列的集合。
        /// </summary>
        [
            Category("数据"), Description("PaginationGrid 中列的集合。"),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
            PersistenceMode(PersistenceMode.InnerProperty),
            Editor(typeof(PaginationGridColumnEditor), typeof(UITypeEditor))
        ]
        public PaginationGridColumnCollection Columns
        {
            get
            {
                if (_columns == null)
                    _columns = new PaginationGridColumnCollection();
                return _columns;
            }
        }


        /// <summary>
        /// 导出到Excel文件中的文件头信息
        /// </summary>
        /// 
        [Browsable(false)]
        public NameValueCollection ExportHeader
        {
            get
            {
                if (ViewState["ExportHeader"] != null)
                {
                    m_ExportHeader = StringToNameValueCollection(ViewState["ExportHeader"].ToString());
                }
                return m_ExportHeader;
            }
            set { ViewState["ExportHeader"] = NameValueCollectionToString(value); }
        }

        /// <summary>
        /// 导出到Excel文件中的页脚信息
        /// </summary>
        /// 
        [Browsable(false)]
        public NameValueCollection ExportFooter
        {
            get
            {
                if (ViewState["ExportFooter"] != null)
                {
                    m_ExportFooter = StringToNameValueCollection(ViewState["ExportFooter"].ToString());
                }
                return m_ExportFooter;
            }
            set { ViewState["ExportFooter"] = NameValueCollectionToString(value); }
        }

        /// <summary>
        /// 控件中引用的资源的路径，通常为IIS根目录下WellDell_client/PaginationGrid/
        /// </summary>
        [Category("行为"), Description("控件中引用的资源的路径"), DefaultValue("~/VitCode_client/PaginationGrid/")]
        public string ResourcePath
        {
            get { return sourcePath; }
            set { sourcePath = value; }
        }

        /// <summary>
        /// 设置表格是否自动生成列，默认不自动生成列。当此值设为true时，表格的列数与数据源中的列数一致。
        /// </summary>
        /// 
        [Category("行为"), Description("表格是否自动生成列。当此值设为true时，表格的列数与数据源中的列数一致。")]
        public bool AutoGenerateColumns { set; get; }

        /// <summary>
        /// 是否具有分页功能
        /// </summary>
        /// 
        [Category("行为"), Description("是否具有分页功能"), DefaultValue(true)]
        public bool AllowPage
        {
            set { ViewState["AllowPage"] = value; }
            get
            {
                if (ViewState["AllowPage"] == null)
                    return true;
                else
                    return Convert.ToBoolean(ViewState["AllowPage"]);
            }
        }

        /// <summary>
        /// 获取或设置是否允许在单击每一列的标头时可以以此列进行排序。当此属性为True时，表格不支持多字段排序。如果设置了属性SortExpression的值为多字段排序方式，则只使用其中的第一个字段排序，其它字段被忽略。
        /// </summary>
        /// 
        [
            Category("行为"),
            Description(
                "是否允许在单击每一列的标头时可以以此列进行排序。当此属性为True时，表格不支持多字段排序。如果设置了属性SortExpression的值为多字段排序方式，则只使用其中的第一个字段排序，其它字段被忽略。")
        ]
        public bool AutoSort
        {
            set { ViewState["AutoSort"] = value; }
            get
            {
                if (ViewState["AutoSort"] == null)
                    return false;
                else
                    return Convert.ToBoolean(ViewState["AutoSort"]);
            }
        }

        /// <summary>
        /// 是否允许将当前页的数据导出到Excel。
        /// </summary>
        [Category("行为"), Description("是否允许将当前页的数据导出到Excel。")]
        public bool ExportCurrentPageDataEnabled
        {
            get { return _ExportCurrentDataEnabled; }
            set { _ExportCurrentDataEnabled = value; }
        }

        /// <summary>
        /// 是否允许将所有数据导出到Excel。
        /// </summary>
        [Category("行为"), Description("是否允许将所有数据导出到Excel。")]
        public bool ExportAllDataEnabled
        {
            get { return _ExportAllDataEnabled; }
            set { _ExportAllDataEnabled = value; }
        }

        /// <summary>
        /// 设置是否显示序号列
        /// </summary>
        /// 
        [Category("行为"), Description("设置是否显示序号列。")]
        public bool ShowIDColumn
        {
            set { showIDColumn = value; }
            get { return showIDColumn; }
        }

        /// <summary>
        /// 设置表格的唯一字段
        /// </summary>
        /// 
        [Category("数据"), Description("设置表格的唯一字段，当表格的列中含有命令列时，此属性必须设置。")]
        public string DataKeyField
        {
            set
            {
                if (m_StandGrid != null)
                    m_StandGrid.DataKeyField = value;
                _DataKeyField = value;
            }
            get { return _DataKeyField; }
        }

        /// <summary>
        /// 获取或设置表格的样式。
        /// </summary>
        [Category("行为"), Description("设置表格样式，当此属性为Custom时，开发人员可以自己定制表格样式")]
        public GridStyle PaginationGridStyle
        {
            set { gridStyle = value; }
            get { return gridStyle; }
        }

        /// <summary>
        /// 获取或设置表格的标题
        /// </summary>
        /// 
        [Category("数据"), Description("表格的标题。"), DefaultValue("")]
        public string GridCaption
        {
            get
            {
                object o = ViewState["GridCaption"];
                if (o != null)
                    return Convert.ToString(ViewState["GridCaption"]);
                else
                    return "";
            }
            set { ViewState["GridCaption"] = value; }
        }

        /// <summary>
        /// 获取或设置表格标题是否可见
        /// </summary>
        /// 
        [Category("行为"), Description("表格标题是否可见。")]
        public bool GridCaptionVisable
        {
            set { gridCaptionVisable = value; }
            get { return gridCaptionVisable; }
        }

        /// <summary>
        /// 获取或设置表格中选中行的背景颜色。
        /// </summary>
        /// 
        [Category("外观"), Description("表格中选中行的背景颜色。")]
        public Color GridSelectedItemStyle_BackColor { get; set; }

        /// <summary>
        /// 获取或设置表格中选中行的文字颜色。
        /// </summary>
        /// 
        [Category("外观"), Description("表格中选中行的文字颜色。")]
        public Color GridSelectedItemStyle_ForeColor { get; set; }

        /// <summary>
        /// 获取或设置表格中选中行的边框颜色。
        /// </summary>
        /// 
        [Category("外观"), Description("表格中选中行的边框颜色。")]
        public Color GridSelectedItemStyle_BorderColor { get; set; }

        /// <summary>
        /// 获取或设置表格体的背景颜色。
        /// </summary>
        /// 
        //		[Category("外观"), Description("表格体的背景颜色")]
        public Color GridBodyBackColor { get; set; }

        /// <summary>
        /// 获取或设置表格体的前景颜色。
        /// </summary>
        /// 
        //		[Category("外观"), Description("表格体的前景颜色")]
        public Color GridBodyForeColor { get; set; }

        /// <summary>
        /// 获取对内部DataGrid的引用。
        /// </summary>
        /// 
        [Browsable(false)]
        public DataGrid CurrentGrid
        {
            get { return m_StandGrid; }
        }

        /// <summary>
        /// 获取当前选择行的索引
        /// </summary>
        /// 
        [Browsable(false)]
        public int SelectedIndex
        {
            get { return m_StandGrid.SelectedIndex; }
        }

        /// <summary>
        /// 获取当前选择行对应的DataKeyField的值
        /// </summary>
        /// 
        [Browsable(false)]
        public string SelectedDataKeyValue
        {
            get { return m_StandGrid.DataKeys[m_StandGrid.SelectedIndex].ToString(); }
        }

        /// <summary>
        /// 获取当前选择的行
        /// </summary>
        /// 
        [Browsable(false)]
        public DataGridItem SelectedItem
        {
            get { return m_StandGrid.SelectedItem; }
        }

        /// <summary>
        /// 当控件的分页模式是“标准”时，设置提供绑定到控件的数据源的委托
        /// </summary>
        /// <seealso cref="VitCode.W.PaginationGrid.BindGrid()"></seealso>
        /// 
        [Browsable(false)]
        public GridDataSourceDelegate DataSourceDelegate
        {
            set { _datasourceDelegate = value; }
        }

        /// <summary>
        /// 当控件的分页模式是“自定义”时，设置提供绑定到控件的数据源构造器的委托
        /// </summary>
        [Browsable(false)]
        public GridDataSourceBuilderDelegate DataSourceBuilderDelegate
        {
            set { _datasourceBuilderDelegate = value; }
        }

        /// <summary>
        /// 设置动态为PaginationGrid创建列的方法委托。通过设置此属性，可以实现在运行过程中动态添加列。此方法应有两个参数：PaginationGrid grid 和 object dataSource。grid参数指明需要操作的PaginationGrid对象，dataSource参数提供了当前PaginationGrid正使用的数据源对象（可能有时需要根据数据源来创建列）。
        /// </summary>
        public GridBuildColumnMethodDelegate BuildColumnMethodDelegate
        {
            set { _buildColumnMethodDelegate = value; }
        }

        /// <summary>
        /// 当响应 OnBeforeExportData 事件后，表格是否继续执行数据导出。
        /// </summary>
        /// 
        [Category("行为"), Description("当响应 OnBeforeExportData 事件后，表格是否继续执行数据导出。")]
        public bool ContinueExport
        {
            get { return m_ContinueExport; }
            set { m_ContinueExport = value; }
        }

        /// <summary>
        /// 设置PaginationGrid的导出文件格式
        /// </summary>
        [Category("数据"), Description("设置PaginationGrid的导出文件格式。")]
        public ExportDataFileFormat DataFileFormat
        {
            get { return m_DataFileFormat; }
            set { m_DataFileFormat = (ExportDataFileFormat)Enum.Parse(typeof(ExportDataFileFormat), value.ToString()); }
        }

        [Category("行为"), Description("是否可以进行打印操作。")]
        public bool IsCanPrint
        {
            get { return m_IsCanPrint; }
            set { m_IsCanPrint = value; }
        }

        #endregion

        #region 

        /// <summary>
        /// 设置表格的样式
        /// </summary>
        /// <param name="pgs">表格样式类</param>
        public void SetGridStyle(PaginationGridStyle pgs)
        {
            EnsureChildControls();
            if (pgs.CssClass != "")
            {
                m_StandGrid.CssClass = pgs.CssClass;
            }
            m_StandGrid.CellPadding = pgs.CellPadding;
            m_StandGrid.CellSpacing = pgs.CellSpacing;
            if (pgs.Style != "")
            {
                m_StandGrid.Attributes.Add("style", pgs.Style);
            }
            m_StandGrid.Width = pgs.Width;
            m_StandGrid.Height = pgs.Height;
            if (pgs.BorderColor != "")
            {
                string color = pgs.BorderColor.Replace("#", "");
                int R = Convert.ToInt32(color.Substring(0, 2), 16);
                int G = Convert.ToInt32(color.Substring(2, 2), 16);
                int B = Convert.ToInt32(color.Substring(4, 2), 16);
                m_StandGrid.BorderColor = Color.FromArgb(R, G, B);
            }
            _TableHeadCssClass = pgs.TableHeadCssClass;
            _TableHeadStyle = pgs.TableHeadStyle;
        }


        /// <summary>
        /// 设置表脚的样式
        /// </summary>
        /// <param name="pgs">表格样式类</param>
        public void SetGridFootStyle(PaginationGridStyle pgs)
        {
            EnsureChildControls();
            if (pgs.CssClass != "")
            {
                BottomTable.Attributes.Add("class", pgs.CssClass);
            }
            BottomTable.CellPadding = pgs.CellPadding;
            BottomTable.CellSpacing = pgs.CellSpacing;
            if (pgs.Style != "")
            {
                //				BottomTable.Attributes.Add("style", pgs.Style);
            }
            if (pgs.BorderColor != "")
            {
                BottomTable.BorderColor = pgs.BorderColor;
            }
            BottomTable.Width = pgs.Width.ToString();
            BottomTable.Height = pgs.Height.ToString();
        }


        /// <summary>
        /// 执行数据绑定并显示数据。
        /// </summary>
        /// <example>
        ///		以下示例展示如何将数据绑定到PaginationGrid控件。
        ///		<para>
        ///			首先，确定PaginationGrid将要使用的分页方式，“标准”还是“自定义”。如果是“标准”方式，请提供一个方法，它必须是以如下方式定义：
        ///			<code>
        ///				private object GetDataSource()
        ///				{
        ///					...
        ///				}
        ///			</code>
        ///			方法必须无参数且返回值类型为 object，如果是“自定义”方式，则方法如下定义：
        ///			<code>
        ///				private PaginationGridDataSourceBuilder GetDataSourceBuilder()
        ///				{
        ///					...
        ///				}
        ///			</code>
        ///			方法必须无参数且返回值类型为 PaginationGridDataSourceBuilder。见<see cref="VitCode.Web.UI.PaginationGridDataSourceBuilder"/>。下面是两种分页方式的方法定义示例
        ///			（假定已在页上定义了两个PaginationGrid控件的实例：PaginationGrid1,PaginationGrid2）：
        ///			<code>
        ///				private object GetPaginationGridData()
        ///				{
        ///					SqlConnection oConn=new SqlConnection("server=127.0.0.1;uid=sa;pwd=sa;database=db");
        ///					oConn.Open();
        ///					DataTable table=new DataTable();
        ///					SqlDataAdapter ad=new SqlDataAdapter("select * from datatable",oConn);
        ///					ad.Fill(table);
        ///					oConn.Close();
        ///					return table;
        ///				}
        ///				private PaginationGridDataSourceBuilder GetPaginationGridDataSourceBuilder_Adapter()
        ///				{
        ///					SqlConnection oConn=new SqlConnection("server=127.0.0.1;uid=sa;pwd=sa;database=db");
        ///					oConn.Open();
        ///					VitCode.Web.UI.AdapterPaginationDataSourceBuilder pb=new AdapterPaginationDataSourceBuilder();
        ///					pb.CommandString="select * from datatable";
        ///					pb.sqlConnection=oConn;
        ///					oConn.Close();
        ///					return pb;	
        ///				}
        ///			</code>
        ///			接下来，在Page_Load方法中，设置PaginationGrid控件的DataSourceDelegat或DataSourceBuilderDelegate属性。在本例中，对PaginationGrid1采用“标准”方式分页，“PaginationGrid2”采用“自定义”方式
        ///			分页。因此添加如下代码：
        ///			<code>
        ///				private void Page_Load(object sender, System.EventArgs e)
        ///				{
        ///					// 在此处放置用户代码以初始化页面
        ///					this.PaginationGrid1.DataSourceDelegate=new VitCode.Web.UI.PaginationGrid.GridDataSourceDelegate(GetPaginationGridData);
        ///					this.PaginationGrid2.DataSourceBuilderDelegate=new VitCode.Web.UI.PaginationGrid.GridDataSourceBuilderDelegate(GetPaginationGridDataSourceBuilder_Adapter);
        ///				}
        ///			</code>
        ///			然后，在需要的地方执行PaginationGrid的BindGrid()方法，实现数据绑定。在体例中，假定已有两个Button控件的实例，点击“Button1”时绑定PaginationGrid1，点击“Button2”时绑定PaginationGrid2，代码如下：
        ///			<code>
        ///				private void Button1_Click(object sender, System.EventArgs e)
        ///				{
        ///					this.PaginationGrid1.BindGrid();
        ///				}
        ///				private void Button2_Click(object sender, System.EventArgs e)
        ///				{
        ///					this.PaginationGrid2.BindGrid();
        ///				}
        ///			</code>
        ///		</para>
        /// </example>
        ///<remarks>
        ///关于分页模式的选择。“标准”分页方式适用于数据量较小的情况，若数据量很大，则用“自定义”分页方式，并再选择一个合适的数据源构造器。见
        ///<see cref="VitCode.Web.UI.PaginationGridDataSourceBuilder"/>
        ///</remarks>
        public void BindGrid()
        {
            BindData(true, 0);
        }

        /// <summary>
        /// 执行数据绑定并显示指定页码的数据。当InitPageIndex的值大于当前数据源所产生的页数时，InitPageIndex的值被视为0，即第一页。
        /// </summary>
        /// <param name="InitPageIndex">绑定后需要显示数据的页码</param>
        public void BindGrid(int InitPageIndex)
        {
            if (InitPageIndex < 0)
                throw new ArgumentOutOfRangeException("InitPageIndex", InitPageIndex, "初始页码必须大于或等于0");
            BindData(true, InitPageIndex);
        }

        /// <summary>
        /// 向表格中增加一个列。
        /// </summary>
        /// <param name="column">一个PaginationGrid列。包括：PaginationGridBoundColumn,PaginationGridLinkColumn,PaginationGridButtonColumn,PaginationGridCheckColumn几种列，如果要自己定义新列，必须从System.Web.UI.WebControls.DataGridColumn继承，且要实现IPaginationGridColumn接口</param>
        /// <example>
        ///	<para>以下示例展示如何在运行时为 PaginationGrid 添加一个PaginationGridBoundColumn列。假设已在页上创建一个PaginationGrid控件的实例，PaginationGrid1</para>
        ///	<code>
        ///		IPaginationGridColumn column=new PaginationGridBoundColumn();
        ///		column.ColumnDataField="名称";
        ///		column.ColumnHeaderText="名称";
        ///		PaginationGrid1.AddColumn(column);
        ///		PaginationGrid1.BindGrid();
        ///	</code>
        ///	<para>注意，上面的方法只是在运行时添加一个列，一旦再次翻页时，新添加的列将丢失。要想每次翻页都能保留动态创建的列，请在页上的 OnInit方法中加入添加列的代码，如：</para>
        ///	<code>
        ///		override protected void OnInit(EventArgs e)
        ///		{
        ///			//
        ///			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
        ///			//
        ///			InitializeComponent();
        ///			IPaginationGridColumn column=new VitCode.Web.UI.PaginationGridBoundColumn();
        ///			column.ColumnDataField="名称";
        ///			column.ColumnHeaderText="名称";
        ///			this.PaginationGrid3.AddColumn(column);
        ///			base.OnInit(e);
        ///		}
        ///	</code>
        ///	<seealso cref="VitCode.Web.UI.IPaginationGridColumn"/>
        /// </example>
        ///
        public void AddColumn(IPaginationGridColumn column)
        {
            Columns.Add(column);
        }

        /// <summary>
        /// 设置每页记录条数列表框的条目
        /// </summary>
        /// <param name="pageSizeOptions">包含一个或多个条目的字符串数组</param>
        /// <param name="initSelectedIndex">列表初始选择项的索引</param>
        public void SetPageSizeOptions(string[] pageSizeOptions, int initSelectedIndex)
        {
            PageSizeOptions = String.Join(",", pageSizeOptions);
            InitPageSize = initSelectedIndex.ToString();
        }

        /// <summary>
        /// 设置每页记录条数列表框的条目
        /// </summary>
        /// <param name="initSelectedIndex">列表初始选择项的索引</param>
        public void SetPageSizeOptions(int initSelectedIndex)
        {
            InitPageSize = initSelectedIndex.ToString();
        }

        /// <summary>
        /// 当表格中有PaginationGridCheckColumn列时,此方法得到被选中的列
        /// </summary>
        /// <param name="colIndex">PaginationGridCheckColumn列在表格中的位置索引</param>
        /// <returns>返回一个由","分隔的字符串,字符串中包含了PaginationGridCheckColumn列中绑定字段的内容</returns>
        public string GetSelectedItem(int colIndex)
        {
            string tempstring = "";
            try
            {
                for (int i = 0; i < m_StandGrid.Items.Count; i++)
                {
                    var lb = new Literal();
                    var chk = new CheckBox();
                    lb = (Literal)m_StandGrid.Items[i].Cells[colIndex].Controls[1];
                    chk = (CheckBox)m_StandGrid.Items[i].Cells[colIndex].Controls[0];
                    if (chk.Checked)
                    {
                        if (tempstring == "")
                        {
                            tempstring += lb.Text;
                        }
                        else
                        {
                            tempstring += "," + lb.Text;
                        }
                    }
                }
            }
            catch
            {
                throw new PaginationGridException("当前表格中没有可以操作的复选框列");
            }
            return tempstring;
        }

        /// <summary>
        /// 当表格中有PaginationGridCheckColumn列时,此方法得到被选中行的在表格中的行索引。与 GetSelectedItemIndex() 方法不同的是，此方法返回选中行在某页以零开始的行索引。
        /// </summary>
        /// <param name="colIndex">PaginationGridCheckColumn列在表格中的位置索引</param>
        /// <returns>回一个由","分隔的字符串,字符串中包含了选中行在某页以零开始的行号</returns>
        public string GetCheckedItemIndex(int colIndex)
        {
            string tempstring = "";
            try
            {
                for (int i = 0; i < m_StandGrid.Items.Count; i++)
                {
                    var chk = new CheckBox();
                    chk = (CheckBox)m_StandGrid.Items[i].Cells[colIndex].Controls[0];
                    if (chk.Checked)
                    {
                        if (tempstring == "")
                        {
                            tempstring += i.ToString();
                        }
                        else
                        {
                            tempstring += "," + i;
                        }
                    }
                }
            }
            catch
            {
                throw new PaginationGridException("当前表格中没有可以操作的复选框列！");
            }
            return tempstring;
        }

        /// <summary>
        /// 当表格中有PaginationGridCheckColumn列时,此方法得到被选中行的行号。与 GetCheckedItemIndex()方法不同的是，此方法返回的行索引是该行在整个数据中的索引，而不是某页的索引。
        /// </summary>
        /// <param name="colIndex">PaginationGridCheckColumn列在表格中的位置索引</param>
        /// <returns>返回一个由","分隔的字符串,字符串中包含了选中行的行号</returns>
        public string GetSelectedItemIndex(int colIndex)
        {
            string tempstring = "";
            try
            {
                for (int i = 0; i < m_StandGrid.Items.Count; i++)
                {
                    var chk = new CheckBox();
                    chk = (CheckBox)m_StandGrid.Items[i].Cells[colIndex].Controls[0];
                    if (chk.Checked)
                    {
                        if (tempstring == "")
                        {
                            tempstring += m_StandGrid.Items[i].Cells[0].Text;
                        }
                        else
                        {
                            tempstring += "," + m_StandGrid.Items[i].Cells[0].Text;
                        }
                    }
                }
            }
            catch
            {
                throw new PaginationGridException("当前表格中没有可以操作的复选框列！");
            }
            return tempstring;
        }

        /// <summary>
        /// 全部选择所有表格中的行
        /// </summary>
        /// <param name="colIndex">PaginationGridCheckColumn列所在表格中的列的位置索引</param>
        public void SelectAllItem(int colIndex)
        {
            bool isExistsChk = false;
            for (int i = 0; i < m_StandGrid.Items.Count; i++)
            {
                try
                {
                    CheckBox chk;
                    chk = (CheckBox)m_StandGrid.Items[i].Cells[colIndex].Controls[0];
                    chk.Checked = true;
                    isExistsChk = true;
                }
                catch
                {
                    throw new PaginationGridException("当前表格中没有可以操作的复选框列！");
                }
                if (isExistsChk == false)
                {
                    break;
                }
            }
        }

        /// <summary>
        /// 取消全选
        /// </summary>
        /// <param name="colIndex">PaginationGridCheckColumn列所在表格中的列的位置索引</param>
        public void UnSelectetAll(int colIndex)
        {
            bool isExistsChk = false;
            for (int i = 0; i < m_StandGrid.Items.Count; i++)
            {
                try
                {
                    CheckBox chk;
                    chk = (CheckBox)m_StandGrid.Items[i].Cells[colIndex].Controls[0];
                    chk.Checked = false;
                    isExistsChk = true;
                }
                catch
                {
                    throw new PaginationGridException("当前表格中没有可以操作的复选框列");
                }
                if (isExistsChk == false)
                {
                    break;
                }
            }
        }

        private ArrayList GenerateExportDataFields(out int[] actualColumnIndexes)
        {
            actualColumnIndexes = new int[m_StandGrid.Columns.Count];
            var fieldList = new ArrayList();
            //生成表头
            int columnCount = m_StandGrid.Columns.Count;
            int columnIndex = 0;
            int actualColumnCount = 0;
            if (!showIDColumn)
            {
                columnIndex = 1;
            }
            for (int i = columnIndex; i < columnCount; i++)
            {
                if (m_StandGrid.Columns[i] is PaginationGridCheckColumn)
                {
                    //若列是PaginationGridCheckColumn ，忽略此列。
                    continue;
                }
                if (m_StandGrid.Columns[i] is PaginationGridButtonColumn)
                {
                    //若列是PaginationGridButtonColumn，并且未设置列的DataTextField属性，则忽略此列。
                    if (((PaginationGridButtonColumn)m_StandGrid.Columns[i]).DataTextField.Trim().Length == 0)
                        continue;
                }
                if (m_StandGrid.Columns[i].Visible == false)
                {
                    //若列已隐藏,忽略此列
                    continue;
                }
                actualColumnIndexes[actualColumnCount] = i;
                actualColumnCount++;
                var column = m_StandGrid.Columns[i] as IPaginationGridColumn;
                var hashtable = new Hashtable();
                hashtable.Add("Field", column.ColumnDataField.ToLower());
                hashtable.Add("ColumnName", FetchDataFieldName(column.ColumnHeaderText));
                fieldList.Add(hashtable);
            }
            return fieldList;
        }

        //private void SetLanguageInfoFroColumns()
        //{
        //    if (Page.GetType().BaseType != null && Page.GetType().BaseType.BaseType != null)
        //    {
        //        Type pageType = Page.GetType().BaseType.BaseType;
        //        MethodInfo mi = pageType.GetMethod("SetPaListlangInfo");
        //        if (mi != null)
        //            mi.Invoke(Page,new object[]{this});
        //    }
        //}

        private void SetLangInfo()
        {
            if (Page.GetType().BaseType != null && Page.GetType().BaseType.BaseType != null)
            {
                Type pageType = Page.GetType().BaseType.BaseType;
                PropertyInfo pi = pageType.GetProperty("LangInfo");
                if (pi != null && pi.CanWrite)
                    pi.SetValue(Page, false, null);
                pi = pageType.GetProperty("LangInfo");
                if (pi != null && pi.CanRead)
                {
                    object objLanInfo = pi.GetValue(Page, null);
                    if (objLanInfo != null && objLanInfo is NameValueCollection)
                    {
                        var nvcLangInfo = ((NameValueCollection)objLanInfo);
                        for (int i = 0; i < nvcLangInfo.Count; i++)
                        {
                            string strKey = nvcLangInfo.GetKey(i);
                            foreach (IPaginationGridColumn col in Columns)
                            {
                                string strColName = col.ColumnHeaderText;
                                strColName = strColName.Replace(strKey, nvcLangInfo.Get(i));
                                col.ColumnHeaderText = strColName;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 将表格中的数据导出到Excel,如果表格有多页数据，此方法只导出当前页
        /// </summary>
        /// <param name="HeaderHTML">表示表头的HTML串</param>
        /// <param name="FileName">要保存客户端的Excel文件名,如:a.xls</param>
        public void ExportCurrentPageDataToExcel(string HeaderHTML, string FileName)
        {
            SetLangInfo();
            int[] actualColumns;
            ArrayList fieldList = GenerateExportDataFields(out actualColumns);
            var table = new DataTable();
            //生成表头
            for (int i = 0; i < fieldList.Count; i++)
            {
                table.Columns.Add(((Hashtable)fieldList[i])["Field"].ToString());
            }
            //生成表体
            for (int j = 0; j < m_StandGrid.Items.Count; j++)
            {
                DataRow row = table.NewRow();
                int colIndex = 0;
                for (int k = 0; k < table.Columns.Count; k++)
                {
                    colIndex = actualColumns[k];
                    switch (m_StandGrid.Columns[colIndex].GetType().Name)
                    {
                        case "PaginationGridLinkColumn":
                            {
                                row[k] =
                                    GetLinkContext(((HyperLink)m_StandGrid.Items[j].Cells[colIndex].Controls[0]).Text).
                                        Replace("&nbsp;", "");
                                break;
                            }
                        case "PaginationGridButtonColumn":
                            {
                                //如果是命令列
                                var btncol = (PaginationGridButtonColumn)m_StandGrid.Columns[colIndex];
                                if (btncol.ButtonType == ButtonColumnType.LinkButton)
                                {
                                    row[k] = ((LinkButton)m_StandGrid.Items[j].Cells[colIndex].Controls[0]).Text;
                                }
                                else
                                {
                                    row[k] = ((Button)m_StandGrid.Items[j].Cells[colIndex].Controls[0]).Text;
                                }
                                break;
                            }
                        case "PaginationGridBoundColumn":
                            {
                                row[k] = GetTitle(m_StandGrid.Items[j].Cells[colIndex].Text).Replace("&nbsp;", "");
                                break;
                            }
                    }
                }
                table.Rows.Add(row);
            }
            //导出到EXCEL
            var factory = new RecordGetterFactory(table);
            IRecordGetter getter = factory.GetRecordGetter();
            getter.DataFilePath = DataFilePath;
            string excelFile;
            switch (DataFileFormat)
            {
                case ExportDataFileFormat.CSV:
                    excelFile = getter.GetRecordAsCSV(fieldList);
                    break;
                case ExportDataFileFormat.HTML:
                    excelFile = getter.GetRecordAsHTML(fieldList);
                    break;
                //				case ExportDataFileFormat.OWC:
                //					excelFile=getter.GetRecordAsOWC(fieldList,this.GridCaption,ExportHeader,ExportFooter);
                //					break;
                default:
                    excelFile = getter.GetRecordAsExcel(fieldList, GridCaption, ExportHeader, ExportFooter);
                    break;
            }
            DownloadFile(excelFile, FileName);
        }

        /// <summary>
        /// 将表格中的数据导出到Excel,如果表格有多页数据，此方法将导出所有页的数据
        /// </summary>
        /// <param name="FileName">要保存客户端的Excel文件名,如:a.xls</param>
        public void ExportAllPageDataToExcel(string FileName)
        {
            SetLangInfo();
            object dataSource = null;
            //字段列表。
            int[] temp;
            ArrayList fieldList = GenerateExportDataFields(out temp);
            if (_paginationMode == PaginationMode.Normal)
            {
                var obj = _datasourceDelegate();
                if (obj != null && obj is DataTable)
                {
                    dataSource = obj;
                }
            }
            else
            {
                dataSource = _datasourceBuilderDelegate().GetAllData(fieldList);
            }
            var factory = new RecordGetterFactory(dataSource);
            IRecordGetter getter = factory.GetRecordGetter();
            getter.DataFilePath = DataFilePath;
            string excelFile;
            switch (DataFileFormat)
            {
                case ExportDataFileFormat.CSV:
                    excelFile = getter.GetRecordAsCSV(fieldList);
                    break;
                case ExportDataFileFormat.HTML:
                    excelFile = getter.GetRecordAsHTML(fieldList);
                    break;
                default:
                    excelFile = getter.GetRecordAsExcel(fieldList, GridCaption, ExportHeader, ExportFooter);
                    break;
            }
            DownloadFile(excelFile, FileName);
        }

        protected string m_TempFrmCallPagePath = "/tempFrmCall.aspx";

        private void DownloadFile(string filePath, string clientFileName)
        {
            
            HttpResponse Response = Page.Response;
            var c = Page.FindControl("tempFrm");
            if (c != null)
            {
                Document.RedirectToFrame(m_TempFrmCallPagePath+"?FilePath=" + HttpUtility.UrlEncode(filePath) + "&ClientFileName=" + HttpUtility.UrlEncode(clientFileName), "tempFrm");
            }
            else
            {
                Response.Clear();
                Response.Charset = "utf-8";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(clientFileName));
                Response.ContentEncoding = Encoding.Default;
                Response.ContentType = "application/ms-excel";
                Response.ContentType = "text/plain";
                Response.ContentType = "application/vnd.ms-excel";
                //Response.ContentType = "text/x-csv";

                var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                if (stream.Length > 10000000)
                {
                    Response.AddHeader("Content-Length", stream.Length.ToString());
                    var readbuffer = new byte[10000];
                    int readlength = 0;
                    try
                    {
                        if (stream.Length > 0)
                        {
                            do
                            {
                                readbuffer.Initialize();
                                readlength = stream.Read(readbuffer, 0, readbuffer.Length);
                                Response.OutputStream.Write(readbuffer, 0, readlength);
                                Response.OutputStream.Flush();
                            } while (readlength > 0 && Response.IsClientConnected);
                            Response.End();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("�ļ�����ʧ�ܣ�" + ex.Message);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
                else
                {
                    stream.Close();


                    //Response.TransmitFile(filePath);
                    //Page.Session["ResponseFilePath"] = filePath;
                    Response.WriteFile(filePath); //此方法发现在下载文件时，会把网页本身的内容一并下载并附加在文件后。停止使用。
                    Response.End();
                }
            }
            
        }

        #endregion

        #region 内部事件响应方法

        private void StandGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            string[] temp = SortExpression.Split(',');
            OldSortField.Text = temp[0].Split(' ')[0];
            if (SortMode.ToLower() == "asc")
            {
                SortMode = "desc";
            }
            else
            {
                SortMode = "asc";
            }
            SortExpression = e.SortExpression + " " + SortMode;
            ShowSortFlag();
            BindData(false, -1);
        }

        private void StandGrid_ItemCreated(object sender, DataGridItemEventArgs e)
        {
            if (m_StandGrid.AutoGenerateColumns)
            {
                return;
            }
            TableCell tcell = e.Item.Cells[0];
            if (_TableHeadCssClass.Length > 0 || _TableHeadStyle.Length > 0)
            {
                if (_TableHeadCssClass.Length > 0)
                {
                    tcell.CssClass = _TableHeadCssClass;
                }
                else
                {
                    //					tcell.Attributes.Add("style", this._TableHeadStyle);
                }
                switch (e.Item.ItemType)
                {
                    case ListItemType.Header:
                        for (int i = 0; i < m_StandGrid.Columns.Count; i++)
                        {
                            TableCell cell = e.Item.Cells[i];
                            if (_TableHeadCssClass.Length > 0)
                            {
                                cell.CssClass = _TableHeadCssClass;
                            }
                            else
                            {
                                //cell.Attributes.Add("style", this._TableHeadStyle);
                            }
                        }
                        break;
                }
            }
            if (IsHaveButtonColumn)
            {
                for (int i = 0; i < m_StandGrid.Columns.Count; i++)
                {
                    if (m_StandGrid.Columns[i].GetType() == typeof(PaginationGridButtonColumn))
                    {
                        var btnCol = (ButtonColumn)m_StandGrid.Columns[i];
                        bool isDelete = btnCol.CommandName.ToLower() ==
                                        PaginationGridButtonColumn.PaginationGridCommandType.Delete.ToString().ToLower();

                        for (int j = 0; j < m_StandGrid.Items.Count; j++)
                        {
                            string strJS = "document.getElementById('" + m_ClickColumnIndex.ClientID + "').value='" + i +
                                           "';";
                            if (isDelete)
                                strJS += "return confirm('确实要删除这条数据吗？');";
                            if (btnCol.ButtonType == ButtonColumnType.LinkButton)
                            {
                                var link = (LinkButton)m_StandGrid.Items[j].Cells[i].Controls[0];

                                link.Attributes.Add("onclick", strJS);
                            }
                            else
                            {
                                var btn = (Button)m_StandGrid.Items[j].Cells[i].Controls[0];
                                btn.Attributes.Add("onclick", strJS);
                            }
                        }
                    }
                }
            }
        }

        private void StandGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                e.Item.Cells[0].Text = "序";
            }
            if ((e.Item.ItemType != ListItemType.Header) && (e.Item.ItemType != ListItemType.Footer))
            {
                e.Item.Cells[0].Text =
                    Convert.ToString(m_StandGrid.CurrentPageIndex * Convert.ToInt32(PageSize.SelectedItem.Text) +
                                     e.Item.ItemIndex + 1);
                for (int i = 0; i < m_StandGrid.Columns.Count; i++)
                {
                    int TextLen = -1;
                    if (AbbColumnList.Items.FindByText(m_StandGrid.Columns[i].HeaderText) != null)
                    {
                        TextLen =
                            Convert.ToInt32(AbbColumnList.Items.FindByText(m_StandGrid.Columns[i].HeaderText).Value);
                    }
                    if (m_StandGrid.Columns[i].GetType() == typeof(PaginationGridBoundColumn))
                    {
                        if (TextLen >= 0 && e.Item.Cells[i].Text.Length > TextLen)
                        {
                            e.Item.Cells[i].Text = "<font title=" + Convert.ToChar(34) + e.Item.Cells[i].Text +
                                                   Convert.ToChar(34) + ">" +
                                                   e.Item.Cells[i].Text.Substring(0, TextLen) + "...</font>";
                        }
                    }
                    if (OnGridShowData != null)
                    {
                        OnGridShowData(this, new PaginationGridShowDataArgs(e.Item.Cells[i], i, e.Item.ItemIndex));
                    }
                }
            }
        }

        /// <summary>
        /// 行选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StandGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (OnGridItemSelect != null)
            {
                var gridItem = new TableRow();
                for (int i = 0; i < m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells.Count; i++)
                {
                    if (m_StandGrid.Columns[i].GetType() == typeof(BoundColumn))
                    {
                        continue;
                    }
                    if (m_StandGrid.Columns[i].GetType() == typeof(PaginationGridCheckColumn))
                    {
                        var tcol = (TemplateColumn)m_StandGrid.Columns[i];
                        if (tcol.ItemTemplate.GetType().Name == "CheckBoxTemplate") //若列带有复选框,返回复选框的选中状态
                        {
                            CheckBox chk;
                            chk = (CheckBox)m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0];
                            var tc = new TableCell();
                            tc.Text = chk.Checked.ToString();
                            gridItem.Cells.Add(tc);
                        }
                        else
                        {
                            var link = (HyperLink)m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0];
                            var tc = new TableCell();
                            tc.Text = link.Text;
                            gridItem.Cells.Add(tc);
                        }
                        continue;
                    }

                    if (m_StandGrid.Columns[i].GetType() == typeof(PaginationGridButtonColumn))
                    {
                        //如果是命令列，返回命令文字
                        var tc = new TableCell();
                        if (m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0].GetType().ToString() ==
                            "System.Web.UI.WebControls.DataGridLinkButton")
                        {
                            var dl = (LinkButton)m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0];
                            tc.Text = dl.Text;
                        }
                        else
                        {
                            var dl = (Button)m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0];
                            tc.Text = dl.Text;
                        }
                        gridItem.Cells.Add(tc);
                        continue;
                    }
                    if (m_StandGrid.Columns[i].GetType() == typeof(PaginationGridBoundColumn))
                    {
                        var tc = new TableCell();
                        tc.Text = GetTitle(m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Text);
                        gridItem.Cells.Add(tc);
                    }
                    else
                    {
                        var tc = new TableCell();
                        tc.Text =
                            GetTitle(
                                ((HyperLink)m_StandGrid.Items[m_StandGrid.SelectedIndex].Cells[i].Controls[0]).Text);
                        gridItem.Cells.Add(tc);
                    }
                }
                try
                {
                    OnGridItemSelect(this,
                                     new PaginationGridItemSelectArgs(m_StandGrid.SelectedIndex, gridItem,
                                                                      m_StandGrid.DataKeys[m_StandGrid.SelectedIndex].
                                                                          ToString(), m_ClickColumnIndex.Value));
                }
                catch (Exception ex)
                {
                    throw new PaginationGridException("可能是没有为表格指定DataKeyField属性,当表格中有命令列,需要设置此属性", ex);
                }
            }
        }

        private void StandGrid_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            if (OnGridItemDelete != null)
            {
                OnGridItemDelete(this,
                                 new PaginationGridItemDeleteArgs(m_StandGrid.DataKeys[e.Item.ItemIndex].ToString()));
            }
        }

        private void PageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            m_StandGrid.CurrentPageIndex = 0;
            BindData(false, -1);
        }

        /// <summary>
        /// 到首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Home_Link_Click(object sender, EventArgs e)
        {
            m_StandGrid.CurrentPageIndex = 0;
            m_StandGrid.SelectedIndex = -1;
            BindData(false, -1);
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Previous_Link_Click(object sender, EventArgs e)
        {
            m_StandGrid.CurrentPageIndex--;
            if (m_StandGrid.CurrentPageIndex < 0)
            {
                m_StandGrid.CurrentPageIndex = 0;
            }
            m_StandGrid.SelectedIndex = -1;
            BindData(false, -1);
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Next_Link_Click(object sender, EventArgs e)
        {
            m_StandGrid.CurrentPageIndex++;
            if (m_StandGrid.CurrentPageIndex > m_StandGrid.PageCount - 1)
            {
                m_StandGrid.CurrentPageIndex = m_StandGrid.PageCount - 1;
            }
            m_StandGrid.SelectedIndex = -1;
            BindData(false, -1);
        }

        /// <summary>
        /// 到尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void End_Link_Click(object sender, EventArgs e)
        {
            m_StandGrid.CurrentPageIndex = m_StandGrid.PageCount - 1;
            BindData(false, -1);
            m_StandGrid.SelectedIndex = -1;
        }

        //跳转页码
        private void toolButton3_Click(object sender, ImageClickEventArgs e)
        {
            if (FormatNumber(PageNo) > 0)
            {
                int page = FormatNumber(PageNo) - 1;
                if (page > m_StandGrid.PageCount - 1)
                {
                    page = m_StandGrid.PageCount - 1;
                }
                m_StandGrid.CurrentPageIndex = page;
                BindData(false, -1);
            }
        }

        //将本页数据导出到EXCEL
        private void toolButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (m_StandGrid.Items.Count == 0)
            {
                return;
            }
            string xlsFileName;
            string ext = "";
            switch (DataFileFormat)
            {
                case ExportDataFileFormat.CSV:
                    ext = ".csv";
                    break;
                default:
                    ext = ".xls";
                    break;
            }
            if (GridCaption == "")
            {
                xlsFileName = "表格数据" + ext;
            }
            else
            {
                xlsFileName = GridCaption.Replace(" ", "") + ext;
            }
            if (OnBeforeExportData != null)
            {
                OnBeforeExportData(this,
                                   new PaginationGridBeforeExportDataArgs(PaginationGridDataExportMode.CurrentPage,
                                                                          GridCaption));
            }
            ExportCurrentPageDataToExcel("", xlsFileName);
        }

        //将所有数据导出到EXCEL
        private void toolButton2_Click(object sender, ImageClickEventArgs e)
        {
            if (m_StandGrid.Items.Count == 0)
            {
                return;
            }
            string xlsFileName;
            string ext = "";
            switch (DataFileFormat)
            {
                case ExportDataFileFormat.CSV:
                    ext = ".csv";
                    break;
                default:
                    ext = ".xls";
                    break;
            }
            if (GridCaption == "")
            {
                xlsFileName = "表格数据" + ext;
            }
            else
            {
                xlsFileName = GridCaption.Replace(" ", "") + ext;
            }
            if (OnBeforeExportData != null)
            {
                OnBeforeExportData(this,
                                   new PaginationGridBeforeExportDataArgs(PaginationGridDataExportMode.All, GridCaption));
                if (m_ContinueExport)
                {
                    ExportAllPageDataToExcel(xlsFileName);
                }
            }
            else
            {
                ExportAllPageDataToExcel(xlsFileName);
            }
        }

        #endregion
    }
}
